package com.hubu.parking.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hubu.parking.constant.ParkConstant;
import com.hubu.parking.entity.park.ParkingRecord;
import com.hubu.parking.entity.park.User;
import com.hubu.parking.entity.sys.SysConfig;
import com.hubu.parking.model.dto.park.ComputeCostDto;
import com.hubu.parking.model.enums.UserRoleEnum;
import com.hubu.parking.service.ParkingRecordService;
import com.hubu.parking.service.SysConfigService;
import com.hubu.parking.service.UserService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@DisallowConcurrentExecution
public class ParkingFeeCalculationJob extends QuartzJobBean {

    @Resource
    private ParkingRecordService recordService;

    @Resource
    private SysConfigService configService;

    @Resource
    private UserService userService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        // 1.列出所有还未完结的订单
        List<ParkingRecord> parkingRecords = recordService.listParingRecordNotEnd();
        // 2.更新endTime和fee
        for (ParkingRecord record : parkingRecords) {
            long start = record.getStartTime().getTime();
            Date nowDate = new Date();
            long nowTime = nowDate.getTime();
            ComputeCostDto computeCostDto = new ComputeCostDto();
            computeCostDto.setStartTime(start);
            computeCostDto.setEndTime(nowTime);
            BigDecimal fee = configService.computeCost(computeCostDto);
            record.setEndTime(nowDate);
            record.setFee(fee);
            recordService.updateById(record);
        }
        SysConfig config = configService.getByName(ParkConstant.BAN_DURATION);
        long dayValue = Integer.parseInt(config.getValue()) * 24 * 60 * 60 * 1000L;
        // 1.查user 封禁
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserRole, UserRoleEnum.BAN.getValue());
        List<User> users = userService.list(queryWrapper);
        for (User user : users) {
            Date updateTime = user.getUpdateTime();
            long updateTimeStamp = updateTime.getTime();
            long current = new Date().getTime();
            if (current - updateTimeStamp > dayValue) {
                user.setUserRole(UserRoleEnum.USER.getValue());
                userService.updateById(user);
            }
        }
    }
}
